package com.nari.ncps.screen.service.impl.al;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nari.ncps.screen.entity.al.AlOverviewItem;
import com.nari.ncps.screen.mapper.al.AlOverviewItemMapper;
import com.nari.ncps.screen.service.al.AlOverviewItemService;
import com.nari.ncps.screen.vo.al.AlOverviewTechIndicatorsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 指标概览表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class AlOverviewItemServiceImpl extends ServiceImpl<AlOverviewItemMapper, AlOverviewItem> implements AlOverviewItemService {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Override
    public AlOverviewTechIndicatorsVO getLatestTechIndicators(Integer year) {

        if (year == null) {
            year = LocalDate.now().getYear();
        }

        //铝产品年产量（铝液）
        String planAmountLY = "0";
        String sql1 = "SELECT plan_amount FROM qt_dp_al_prodoper_prd_sit_ly " +
        "WHERE org_code = '100360' AND date_type='0' AND year = ?  limit  1 " ;
        try {
            planAmountLY = jdbcTemplate.queryForObject(sql1, String.class,year);//年计划总量
        } catch (EmptyResultDataAccessException e) {
            planAmountLY = "0";
        }

        //铝产品年产量（铝锭）
        String planAmountLD = "0";
        String sql2 = "SELECT plan_amount FROM qt_dp_al_prodoper_prd_sit_ld " +
                "WHERE org_code = '100360' AND date_type='0' AND year = ?  limit  1 " ;
        try {
            planAmountLD = jdbcTemplate.queryForObject(sql2, String.class,year);//年计划总量
        } catch (EmptyResultDataAccessException e) {
            planAmountLD = "0";
        }

        //碳素阳极年产量
        String planAmountTSYJ = "0";
        String sql3 = "SELECT plan_amount FROM qt_dp_al_prodoper_prd_sit_tsyj " +
                "WHERE org_code = '100360' AND date_type='0' AND year = ?  limit  1 " ;
        try {
            planAmountTSYJ = jdbcTemplate.queryForObject(sql3, String.class,year);
        } catch (EmptyResultDataAccessException e) {
            planAmountTSYJ = "0";
        }

        //碳素阳极日产量
        String planAmountTSYJDAY = "0";
        String sql4 = "SELECT plan_amount FROM qt_dp_al_prodoper_prd_sit_tsyj " +
                "WHERE org_code = '100360' AND date_type='2' AND year = ?  limit  1 " ;
        try {
            planAmountTSYJDAY = jdbcTemplate.queryForObject(sql4, String.class,year);
        } catch (EmptyResultDataAccessException e) {
            planAmountTSYJDAY = "0";
        }

        BigDecimal planAmountDJLCNYEAR = new BigDecimal(0);//电解铝年产能(万吨)
        BigDecimal planAmountDJLCNYEARRATE = new BigDecimal(0);//电解铝产能利用率(%)
        BigDecimal alSalesYearly = new BigDecimal(0);//电解铝销量(万吨)
//        BigDecimal alSalesYearly2 = new BigDecimal(0);//电解铝销量(万吨)
        BigDecimal alWaterConversionRate = new BigDecimal(0);//铝水就地转化率(%)
        BigDecimal recycleResourceRate = new BigDecimal(0);//可再生能源产能

        //qt_dp_al_overview_item_yxcn  电解铝销量

        String sql5 = "SELECT al_capacity_yearly,al_capacity_utilization,al_sales_yearly,al_water_conversion_rate,recycle_resource_rate FROM qt_dp_al_overview_item " +
                "WHERE org_code = '100360' AND date_type='0' AND year = ?  limit  1 " ;
        try {
            Map<String, Object> resultMap = jdbcTemplate.queryForMap(sql5, year);

//            planAmountDJLCNYEAR = resultMap.get("al_capacity_yearly") != null ?
//                    new BigDecimal(resultMap.get("al_capacity_yearly").toString()) : BigDecimal.ZERO;

            planAmountDJLCNYEARRATE = resultMap.get("al_capacity_utilization") != null ?
                    new BigDecimal(resultMap.get("al_capacity_utilization").toString()) : BigDecimal.ZERO;

//            alSalesYearly = resultMap.get("al_sales_yearly") != null ?
//                    new BigDecimal(resultMap.get("al_sales_yearly").toString()) : BigDecimal.ZERO;

            alWaterConversionRate = resultMap.get("al_water_conversion_rate") != null ?
                    new BigDecimal(resultMap.get("al_water_conversion_rate").toString()) : BigDecimal.ZERO;

            recycleResourceRate = resultMap.get("recycle_resource_rate") != null ?
                    new BigDecimal(resultMap.get("recycle_resource_rate").toString()) : BigDecimal.ZERO;

        } catch (EmptyResultDataAccessException  e) {
            e.printStackTrace();
        }

        //电解铝产能
        String alOperatingCapacity = "0";
        String sql6 = "SELECT al_operating_capacity FROM qt_dp_al_overview_item_yxcn " +
                "WHERE org_code = '100360' AND date_type='0' AND product_type='01' AND year = ?  limit  1 " ;
        try {
            alOperatingCapacity = jdbcTemplate.queryForObject(sql6, String.class,year);
        } catch (EmptyResultDataAccessException e) {
            alOperatingCapacity = "0";
        }

        //电解铝销量
        String actualSales = "0";
        String sql7 = "SELECT month_actual_sales FROM qt_dp_al_prodoper_sales " +
                "WHERE org_code = '100360' AND date_type='0' AND product_type='01' AND year = ?  limit  1 " ;
        try {
            actualSales = jdbcTemplate.queryForObject(sql7, String.class,year);
        } catch (EmptyResultDataAccessException e) {
            actualSales = "0";
        }

        // 转换为VO对象
        AlOverviewTechIndicatorsVO vo = new AlOverviewTechIndicatorsVO();
        vo.setAlProductionYearly((planAmountLY != null ? new BigDecimal(planAmountLY) : BigDecimal.ZERO).add((planAmountLY != null ? new BigDecimal(planAmountLD) : BigDecimal.ZERO)));
//        vo.setAlProductionYearly(alOperatingCapacity != null ? new BigDecimal(alOperatingCapacity) : BigDecimal.ZERO);
//        vo.setAlCapacityYearly(planAmountDJLCNYEAR);
        vo.setAlCapacityYearly(alOperatingCapacity != null ? new BigDecimal(alOperatingCapacity) : BigDecimal.ZERO);

        vo.setCarbonProductionYearly(planAmountTSYJ != null ? new BigDecimal(planAmountTSYJ) : BigDecimal.ZERO);
        vo.setCarbonCapacityYearly(planAmountTSYJDAY != null ? new BigDecimal(planAmountTSYJDAY) : BigDecimal.ZERO);
        vo.setAlCapacityUtilization(planAmountDJLCNYEARRATE);
//        vo.setAlSalesYearly(alSalesYearly2 != null ? new BigDecimal(alSalesYearly2) : BigDecimal.ZERO);
        vo.setAlSalesYearly(actualSales != null ? new BigDecimal(actualSales) : BigDecimal.ZERO);
        vo.setAlWaterConversionRate(alWaterConversionRate);
        vo.setProportionOfRenewableEnergy(recycleResourceRate);

        return vo;
    }
    
    /**
     * 检查数据是否有效（至少有一个字段有值）
     */
    private boolean hasValidData(AlOverviewItem item) {
        return item.getAlProductionYearly() != null ||
               item.getAlCapacityYearly() != null ||
               item.getCarbonProductionYearly() != null ||
               item.getCarbonCapacityYearly() != null ||
               item.getAlCapacityUtilization() != null ||
               item.getAlSalesYearly() != null ||
               item.getAlWaterConversionRate() != null;
    }
    
    /**
     * 生成mock综合技术指标数据
     * 覆盖铝业产业的各项技术指标
     */
    private AlOverviewTechIndicatorsVO generateMockTechIndicators() {
        AlOverviewTechIndicatorsVO vo = new AlOverviewTechIndicatorsVO();
        
        // 铝产品年产量(万吨) - 设置为120-150万吨
        vo.setAlProductionYearly(BigDecimal.valueOf(135.5).setScale(1, RoundingMode.HALF_UP));
        
        // 电解铝年产能(万吨) - 设置为150-180万吨，应大于产量
        vo.setAlCapacityYearly(BigDecimal.valueOf(165.0).setScale(1, RoundingMode.HALF_UP));
        
        // 炭素年产量(万吨) - 设置为50-70万吨
        vo.setCarbonProductionYearly(BigDecimal.valueOf(58.8).setScale(1, RoundingMode.HALF_UP));
        
        // 炭素产能(万吨) - 设置为70-90万吨，应大于产量
        vo.setCarbonCapacityYearly(BigDecimal.valueOf(75.0).setScale(1, RoundingMode.HALF_UP));
        
        // 电解铝产能利用率(%) - 计算：产量/产能*100
        BigDecimal utilizationRate = vo.getAlProductionYearly()
                .divide(vo.getAlCapacityYearly(), 4, RoundingMode.HALF_UP)
                .multiply(BigDecimal.valueOf(100))
                .setScale(2, RoundingMode.HALF_UP);
        vo.setAlCapacityUtilization(utilizationRate);
        
        // 电解铝销量(万吨) - 设置为产量的90%-100%
        vo.setAlSalesYearly(BigDecimal.valueOf(128.3).setScale(1, RoundingMode.HALF_UP));
        
        // 铝水就地转化率(%) - 设置为75%-85%
        vo.setAlWaterConversionRate(BigDecimal.valueOf(79.5).setScale(2, RoundingMode.HALF_UP));
        
        return vo;
    }

}
